package com.neusoft.bizcore.notice.system.repository.impl;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.notice.system.model.QSystemNotice;
import com.neusoft.bizcore.notice.system.model.SystemNotice;
import com.neusoft.bizcore.notice.system.model.enums.SystemNoticeStatus;
import com.neusoft.bizcore.notice.system.repository.CustomizedSystemNoticeRepository;
import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedSystemNoticeRepositoryImpl extends AbstractRepository
        implements CustomizedSystemNoticeRepository {

    @Override
    public List<SystemNotice> index(final Searchable searchable) {
        final QSystemNotice qSystemNotice = QSystemNotice.systemNotice;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<SystemNotice> query = this.query().selectFrom(qSystemNotice);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<SystemNotice> search(final Pageable pageable, final Searchable searchable) {
        final QSystemNotice qSystemNotice = QSystemNotice.systemNotice;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<SystemNotice> query = this.query().selectFrom(qSystemNotice);
        query.where(where);
        return super.search(query, pageable);
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QSystemNotice qSystemNotice = QSystemNotice.systemNotice;

        where.and(super.containsStr(qSystemNotice.appCode, searchable, "appCode"));
        where.and(super.containsStr(qSystemNotice.content, searchable, "content"));
        where.and(super.containsStr(qSystemNotice.noticeType, searchable, "noticeType"));
        where.and(super.containsStr(qSystemNotice.user.user, searchable, "user"));
        where.and(
                super.equalsEnum(qSystemNotice.isRead, searchable, "isRead",
                        value -> SystemNoticeStatus.valueOf(value)));
        return where;
    }

    @Override
    protected Class<?> getModelClass() {
        return SystemNotice.class;
    }

    @Override
    public List<String> findDistinctNoticeType() {
        final QSystemNotice qSystemNotice = QSystemNotice.systemNotice;
        final JPAQuery<String> dquery =
                this.query().select(qSystemNotice.noticeType).from(qSystemNotice).distinct();
        return dquery.fetch();
    }

}
